package com.lzp.java.concurrent.buildcache;

import java.util.HashMap;
import java.util.Map;

/**
 * @author lzp
 * @Description: 1. 使用装饰者解耦缓存与缓存计算操作
 * 2. synchronized会影响性能，但是仅同步compute操作线程不安全
 * @date 2021/3/14
 */
public class Cache2<K, V> implements Computable<K, V> {
    private final Map<K, V> cache = new HashMap<>();
    private final Computable<K, V> c;

    public Cache2(Computable<K, V> c) {
        this.c = c;
    }

    @Override
    public synchronized V compute(K key) throws Exception {
        V result = cache.get(key);
        if (result == null) {
            result = c.compute(key);
            cache.put(key, result);
        }
        return result;
    }

    public static void main(String[] args) throws Exception {
        Cache2<String, Integer> cache1 = new Cache2<>(new ComputableImpl());
        System.out.println(cache1.compute("key"));
        System.out.println(cache1.compute("key"));
    }
}
